package com.czk.shop.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.comon.czk.constant.ShopCode;
import com.comon.czk.entity.Result;
import com.comon.czk.exception.CastException;
import com.czk.api.IGoodsService;
import com.czk.shop.mapper.TradeGoodsMapper;
import com.czk.shop.mapper.TradeGoodsNumberLogMapper;
import com.czk.shop.pojo.TradeGoods;
import com.czk.shop.pojo.TradeGoodsNumberLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 商品的实现类
 * @Author:ChenZhangKun
 * @Date: 2020/9/18 21:12
 */
@Component
@Service(interfaceClass = IGoodsService.class)
public class IGoodsServiceImpl implements IGoodsService {
    @Autowired
    private TradeGoodsMapper tradeGoodsMapper;
    @Autowired
    private TradeGoodsNumberLogMapper tradeGoodsNumberLogMapper;
    @Override
    public TradeGoods findOne(Long goodsId) {
        if (goodsId==null){
            CastException.cast(ShopCode.SHOP_REQUEST_PARAMETER_VALID);
        }
         return tradeGoodsMapper.selectByPrimaryKey(goodsId);
    }

    @Override
    public Result reduceNum(TradeGoodsNumberLog goodsNumberLog) {
        // 参数校验
        if (goodsNumberLog==null||goodsNumberLog.getGoodsNumber()==null||goodsNumberLog.getOrderId()==null||goodsNumberLog.getGoodsNumber().intValue()<=0){
            CastException.cast(ShopCode.SHOP_REQUEST_PARAMETER_VALID);
        }
        // 扣减库存
        TradeGoods tradeGoods = tradeGoodsMapper.selectByPrimaryKey(goodsNumberLog.getGoodsId());
        // 库存不足
        if (tradeGoods.getGoodsNumber()<goodsNumberLog.getGoodsNumber()){
            // 库存不足
            CastException.cast(ShopCode.SHOP_GOODS_NUM_NOT_ENOUGH);
        }
        // 扣减库存
        tradeGoods.setGoodsNumber(tradeGoods.getGoodsNumber()-goodsNumberLog.getGoodsNumber());
        // 更新
        tradeGoodsMapper.updateByPrimaryKey(tradeGoods);
        // 记录库存操作日志
        goodsNumberLog.setLogTime(new Date());
        tradeGoodsNumberLogMapper.insert(goodsNumberLog);
        return new Result(ShopCode.SHOP_SUCCESS.getSuccess(),ShopCode.SHOP_SUCCESS.getMessage());
    }
}
